import React, { useState, useEffect} from 'react';
import './User.css'; // 样式
import { ReactComponent as FollowIcon } from '../assets/icons/Follow.svg'; // 关注图标
import { ReactComponent as FollowedIcon } from '../assets/icons/Followed.svg'; // 已关注图标
import defaultAvatar from '../assets/images/默认头像.jpg';
import { useNavigate } from 'react-router-dom';
import { follow, unfollow} from '../api/userApi'; // 调整路径

const User = ({ user }) => {
  const [isFollow, setIsFollow] = useState(user.isFollow); // 默认未关注
  const navigate = useNavigate();
  const [userId, setUserId] = useState(localStorage.getItem('userId')); // 获取当前用户 ID
  // 获取用户 ID
  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    }
  }, []);

  if (!user) {
      return <div>暂无相关用户</div>; // 处理数据加载失败的情况
   }
  // 点击跳转到用户详情页
  const UserDetails = () => {  
    navigate(`/personal/${user.userId}`); // 使用 userId 跳转
  };
  
   // 切换关注状态函数
   const toggleFollow = async () => {
    if (isFollow) {
        const response = await unfollow(userId, user.userId); // 取消关注
        if (response.success) {
            setIsFollow(false);
        } else {
            console.error(response.error);
        }
    } else {
        const response = await follow(userId, user.userId); // 执行关注
        if (response.success) {
            setIsFollow(true);
        } else {
            console.error(response.error);
        }
    }
  };


  const avatarSrc = user.image ? 'http://localhost:8080/'+user.image : defaultAvatar;

  return (
    <div className="user">
      <div className="user-header" >
        {/* 左侧：用户头像 */}
        <img className="user-avatar-img-result" src={avatarSrc} alt="avatar" onClick={UserDetails} />
        <div className="user-info">
          <span className="user-name">{user.account || '未知用户'}</span>
          <p className="user-id">ID: {user.userId || 'N/A'}</p>
          <p className="user-bio">{user.signature || '暂无个人简介'}</p>
        </div>
        {userId && user.userId && userId !== String(user.userId) && (
        <button 
          className={`follow-btn ${isFollow? 'followed' : 'not-followed'}`} 
          onClick={toggleFollow}
        >
          {isFollow ? (
            <div className='follow-btn-inner-followed'>
              <span>已关注</span>
            </div>
          ) :( 
            <div className='follow-btn-inner-not-followed'>
              <span>关注</span>
            </div>
          )}
          {isFollow ? (
            <FollowedIcon className="follow-icon" />
          ) : (
            <FollowIcon className="follow-icon" />
          )}
        </button>
        )}
      
      </div>
    </div>
  );
};

export default User;
